package dao;

import model.User;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao { // 用户数据访问实现 完成人：姜凯严、邓亦明 7/5
    private static final String DB_URL = "jdbc:sqlite:redwine.db";

    @Override
    public User findByUsernameAndPassword(String username, String password) { // 登录
        String sql = "SELECT user_id, username, password, address, phone, balance, permission_level FROM user WHERE username = ? AND password = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                User user = new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setAddress(rs.getString("address"));
                user.setPhone(rs.getString("phone"));
                user.setBalance(rs.getDouble("balance"));
                user.setPermissionLevel(rs.getString("permission_level"));
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User findById(int userId) { // 根据ID查找用户
        String sql = "SELECT user_id, username, password, address, phone, balance, permission_level FROM user WHERE user_id = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                User user = new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setAddress(rs.getString("address"));
                user.setPhone(rs.getString("phone"));
                user.setBalance(rs.getDouble("balance"));
                user.setPermissionLevel(rs.getString("permission_level"));
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<User> findAll() { // 查询所有用户
        List<User> list = new ArrayList<>();
        String sql = "SELECT user_id, username, password, address, phone, balance, permission_level FROM user";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                User user = new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setAddress(rs.getString("address"));
                user.setPhone(rs.getString("phone"));
                user.setBalance(rs.getDouble("balance"));
                user.setPermissionLevel(rs.getString("permission_level"));
                list.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public boolean addUser(User user) { // 添加用户
        String sql = "INSERT INTO user (username, password, address, phone, balance, permission_level) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getAddress());
            pstmt.setString(4, user.getPhone());
            pstmt.setDouble(5, user.getBalance());
            pstmt.setString(6, user.getPermissionLevel().name());
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean updateUser(User user) { // 修改用户
        String sql = "UPDATE user SET username=?, password=?, address=?, phone=?, balance=?, permission_level=? WHERE user_id=?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getAddress());
            pstmt.setString(4, user.getPhone());
            pstmt.setDouble(5, user.getBalance());
            pstmt.setString(6, user.getPermissionLevel().name());
            pstmt.setInt(7, user.getUserId());
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean deleteUser(int userId) { // 删除用户
        String sql = "DELETE FROM user WHERE user_id=?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public List<User> findByUsername(String username) { // 根据用户名查找用户
        List<User> list = new ArrayList<>();
        String sql = "SELECT user_id, username, password, address, phone, balance, permission_level FROM user WHERE username = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setAddress(rs.getString("address"));
                user.setPhone(rs.getString("phone"));
                user.setBalance(rs.getDouble("balance"));
                user.setPermissionLevel(rs.getString("permission_level"));
                list.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<User> findByPhone(String phone) { // 根据电话查找用户
        List<User> list = new ArrayList<>();
        String sql = "SELECT user_id, username, password, address, phone, balance, permission_level FROM user WHERE phone = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, phone);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setAddress(rs.getString("address"));
                user.setPhone(rs.getString("phone"));
                user.setBalance(rs.getDouble("balance"));
                user.setPermissionLevel(rs.getString("permission_level"));
                list.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<User> findByUsernameAndPhone(String username, String phone) { // 根据用户名和电话查找用户
        List<User> list = new ArrayList<>();
        String sql = "SELECT user_id, username, password, address, phone, balance, permission_level FROM user WHERE username = ? AND phone = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, phone);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setAddress(rs.getString("address"));
                user.setPhone(rs.getString("phone"));
                user.setBalance(rs.getDouble("balance"));
                user.setPermissionLevel(rs.getString("permission_level"));
                list.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public boolean addUser(String username, String password) { // 添加用户（仅用户名和密码）
        String sql = "INSERT INTO user (username, password, address, phone, balance, permission_level) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(DB_URL);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.setString(3, ""); // 地址默认为空
            pstmt.setString(4, ""); // 电话默认为空
            pstmt.setDouble(5, 0.0); // 余额默认为0
            pstmt.setString(6, User.PermissionLevel.normal.name()); // 默认为普通用户权限
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
